package org.bwapi.bridge.util;

import java.util.ServiceLoader;

import org.bwapi.bridge.BridgeBot;
import org.bwapi.bridge.BridgeBotFactory;
import org.bwapi.bridge.model.Game;


/**
 * Delegation method to load the bot
 * 
 * @author Chad Retz
 */
public class BridgeDelegator {
	
	private static final ServiceLoader<BridgeBotFactory> SERVICE_LOADER =
		ServiceLoader.load(BridgeBotFactory.class);
	
	/**
	 * Load the bot; if not bots are found, {@link NopBot} is used.
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static final BridgeBot load() {
		//wait a minute, is my test factory on the classpath?
		try {
			Class<? extends BridgeBotFactory> factory = (Class<? extends BridgeBotFactory>) 
					Class.forName("org.bwapi.unit.client.BwapiTestBotFactory");
			Game.getInstance().printf("Found test factory");
			//oh it is?
			try {
				BridgeBot bot = factory.newInstance().getBridgeBot(Game.getInstance());
				if (bot == null) {
					Game.getInstance().printf("No test bot found!");
				} else {
					return bot;
				}
			} catch (Exception e) {
				Game.getInstance().printf("Can't instantiate test: " + e.getMessage());
			}
		} catch (ClassNotFoundException e) {
			//who cares...
		}
		for (BridgeBotFactory factory : SERVICE_LOADER) {
			BridgeBot bot = factory.getBridgeBot(Game.getInstance());
			if (bot != null) {
				return bot;
			}
		}
		return new NopBot();
	}
}
